<?php

namespace app\manage\services;

use app\common\loader\ModelMerchant;
use app\common\loader\ModelPromo;
use app\common\loader\ModelSystem;
use app\common\loader\ModelVirtual;
use app\common\validate\merchant\MerchantValid;
use app\manage\loader\ManageServices;
use think\db\exception\DbException;
use think\Exception;

/**
 * 系统相关
 */
class SystemService extends BaseService
{
    /**
     * 系统日志
     * @param array $options
     * @return mixed
     * @throws Exception
     * @throws \think\db\exception\DbException
     */
    public function systemLog(array $options)
    {
        $options['order'] = 'id desc';
        $options['without_field'] = 'request,execute';
        return ModelSystem::SystemOplog()->page($options);
    }

    /**
     * 首页管理员统计
     * @param $date |day 昨天， month/上月
     * @param $page
     * @param $page_size
     * @return mixed
     * @throws DbException
     */
    public function systemAdminHome($date, $time, $page , $page_size)
    {
        $where =  $this->formatAdminOption($date,$time);
        return ModelSystem::SystemManager()->getAdminStatisticData(
            $where['db_table'],
            $where['where'],
            $page ,
            $page_size);
    }
    //管理员/商户条件
    private  function  formatAdminOption($date = 'day',$time = ''){
        $result = [
            'db_table' => 'merchant_statistic_day', //表名称
            'where' => [], //时间条件
        ];
        $dbName = ['day' => 'merchant_statistic_day' , 'month' => 'merchant_statistic_month'];
        $result['db_table'] = $dbName[$date];

        if (!empty($time)){
            $result['where'] = ['statistics_date' => $time];
            return $result;
        }

        if ((string)$date === 'day'){
            $result['where'] = ['statistics_date' => (string)date('Y-m-d',strtotime('-1 day'))];
        }

        if ((string)$date === 'month'){
            $result['where'] = ['statistics_date' => (string)date('Y-m')];
        }
        return $result;
    }



    /**
     * 首页商户统计
     * @param $date |day 昨天， month/上月
     * @param $page
     * @param $page_size
     * @return mixed
     */
    public function systemMerchantHome($date, $time,$page , $page_size,$mer_id='')
    {
        $where =  $this->formatAdminOption($date,$time);
        if(!empty($mer_id)){
            $where['where']['mer_id'] = $mer_id;
        }
        return ModelMerchant::MerchantStatistic()->getMerchantStatisticData(
            $where['db_table'],
            $where['where'],
            $page ,
            $page_size);
    }

    /**
     * 账户余额，充值金额 | 金额明细
     * @param $date |day 昨天， month/上月
     * @param $page
     * @param $page_size
     * @return mixed
     * @throws DbException
     */
    public function systemMerchantDetailHome($mer_id ,$date,$time, $page , $page_size)
    {
        $where =  $this->formatMerchantOption($mer_id,$date,$time);
        return ModelMerchant::MerchantMoneyLog()->pages(
            $where['where'],
            $page ?? 1,
            $page_size ?? 30);

    }

    //金额明细/商户条件
    private  function  formatMerchantOption($mer_id ,$date , $time, $manager = ''){
        $result = [
            'where' => [],//条件
        ];
        $dateDay = date('Y-m-d');

        if ((string)$date === 'day'){
            $etime = $time.' 23:59:59';
            $stime = $time.' 00:00:00';
        }

        if ((string)$date === 'month'){
            $date_time = date('Y-m');
            $stime = $time.'-01 00:00:00';
            $etime = date('Y-m-d', strtotime("$stime +1 month -1 day")) . ' 23:59:59';
            if ((string)$date_time === (string)$time){
                $etime = date('Y-m-d', strtotime("-1 day")) . ' 23:59:59';
            }

        }

        if ($stime > $dateDay){
            throw  new Exception('无大于昨日数据', API_ERROR);
        }

        $result['where'] =  $this->actionWhere('create_at',$stime, $etime);
        $result['where'][] =  ['mer_id' , '=' , $mer_id];
        if (!empty($manager)){
            $result['where'][] =  ['status' , 'in' , [8]];
        }
        return $result;
    }


    private  function  actionWhere($filed , $stime = '' , $etime = ''){

        $wheres = [];
        if (!empty($stime) && !empty($etime)) {
            $wheres[] = [$filed, 'between', [$stime, $etime]];
        } else {
            if (!empty($stime)) {
                $wheres[] = [$filed, '>=', $stime];
            }
            if (!empty($etime)) {
                $wheres[] = [$filed, '<=', $etime];
            }
        }

        return $wheres;
    }

    /**
     * （导购发出红包）导购扫码发出红包
     * @param $date |day 昨天， month/上月
     * @param $page
     * @param $page_size
     * @return mixed
     * @throws DbException
     */
    public function systemManagerFundHome($mer_id ,$date, $time,$page , $page_size)
    {
        $where =  $this->formatMerchantOption($mer_id,$date,$time,'manager');
        $where['page_size'] = ['page' => $page, 'list_rows' => $page_size];
        $pageList = ModelVirtual::VirtualUsedLog()->statisticpage($mer_id, $where);
        $ServiceHelper = \app\common\loader\Services::Helper();
        $ServiceHelper->showListTitle($pageList['data'],
            ['salesman' => 'salesman_id']);
        return $pageList;
    }

    /**
     * 首页
     * @param $options
     * @return mixed
     * @throws Exception
     * @throws DbException
     */
    public function systemHome($options)
    {
        $options = $this->formatHomeOption($options);
        return ModelSystem::SystemOplog()->home($options);
    }

    //首页条件
    private  function  formatHomeOption($date){

        $result = [
            'log_where' => [], // update_at 日志使用条件
            'where' => [], // create_at  时间条件
            'wheres' => [], // begin_time 时间条件
            'info_where' => [], // begin_time 时间条件
            'stock_where' => [], // update_at 时间条件
        ];

        $etime = date('Y-m-d',strtotime('-1 day')) . ' 23:59:59';
        $stime = date("Y-m-d",strtotime('-1 day')) . ' 00:00:00';
        if ((string)$date !== 'day'){
            $date_time = date('Y-m');
            $stime = $date_time.'-01 00:00:00';
            $etime = date('Y-m-d', strtotime("-1 day")) . ' 23:59:59';
        }

        $result['where'] =  $this->actionWhere('create_at',$stime, $etime);

        $result['wheres'] =   $this->actionWhere('begin_time',$stime, $etime);

        $result['log_where'] =  $result['where'];

        $result['info_where'] = $result['wheres'];

        $result['stock_where'] = $this->actionWhere('update_at',$stime, $etime);

        return $result;
    }
}
